import time,datetime
from 组件.notice import show_notification_thread, init_notification_system
from 组件.sqlite import SimpleSQLite
from 主程.公共函数 import get_stock,need_notice,add_notice,update_notice
from 主程.基础配置 import settings

stock_span = {stock["all_code"]: stock["span"] for stock in settings.STOCK_CODE}

def order_watch(self):
    ##买入检测

    ##撤单检测
    notice = False
    filled_orders_sorted, no_filled_orders = self.get_orders()  # 修改这里，接收3个返回值
    print("未成交挂单检测运行中......")


    for order in no_filled_orders:
        stock_code = order.stock_code
        msg = f"订单 {order.order_sysid}"

        if order.order_type == 23:
            ## 买入监测撤单提醒
            # 检测10分钟没买入撤销
            current_time = datetime.datetime.now().timestamp()  # 当前时间戳
            time_diff = current_time - order.order_time  # 计算时间差（秒）
            if time_diff > 600:  # 超过10分钟（600秒）买入未成交
                msg += "超时,"
                notice = True

            # 跳出波段内则取消订单
            with SimpleSQLite("../组件/data/stock.db") as db:
                current_time = time.time()
                today = datetime.datetime.fromtimestamp(current_time).strftime("%Y-%m-%d")
                # 查询最新的未结束的震荡区间
                data = db.fetch_one(
                    "SELECT * FROM stock_updown WHERE stock_code = ? AND date = ? ORDER BY id DESC LIMIT 1",
                    (order.stock_code, today))
                if data:
                    start_time_str = data["start_time"]
                    # 将日期和时间组合起来计算
                    start_datetime = datetime.datetime.strptime(start_time_str, "%Y-%m-%d %H:%M:%S")
                    duration = current_time - start_datetime.timestamp()
                    if duration > 420:  # 7分钟=420秒
                        print(f"波动开始时间:{start_datetime}")
                        msg += "跳出区间,"
                        notice = True
                else:
                    print("无波动数据")

            # 收盘前时间判断
            now = datetime.datetime.now()
            current_hour = now.hour
            current_minute = now.minute

            # 上午收盘前半小时（11:00后禁止买入）
            if (current_hour == 11 and current_minute >= 0) or (current_hour > 11 and current_hour < 13):
                msg += "尾盘,"
                notice = True

            # 下午收盘前半小时（14:30后禁止买入）
            if (current_hour == 14 and current_minute >= 30) or current_hour >= 15:
                msg += "尾盘,"
                notice = True
        else:
            ##卖出止损提醒，需要获取实时价格，如果跌过3%则市价平
            data = get_stock(stock_code)
            now_price = data["now_price"]
            ##print(f"订单 {order.order_sysid}挂单价格{order.price},检测最新价格 {now_price}")
            span = stock_span.get(stock_code)
            if float(now_price) <= float(order.price) - float(span*settings.GIVE_SPAN):
                notice = True
                msg += "跌幅警告,"
                if order.order_remark == "反手卖出":
                    self.modify_to_market_order(order.order_sysid)
            # 检测10分钟没卖出
            current_time = datetime.datetime.now().timestamp()  # 当前时间戳
            time_diff = current_time - order.order_time  # 计算时间差（秒）
            if time_diff > 600:  # 超过10分钟（600秒）买入未成交
                msg += "卖出超时,"
                notice = True

        if notice:
            need = need_notice(order.order_sysid,msg)
            if need ==0:
                add_notice(order.order_sysid,msg)
            if need==1:
                print(msg)
                update_notice(order.order_sysid,msg)
                show_notification_thread("撤单提醒", msg)
        else:
            print("挂单检测正常")


